import Toast, { hideToast } from 'tdesign-miniprogram/toast'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    post: null,
    user: null,
    postActions: [],
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({id}) {
    if (id) {
      this.data.id = id
      this.getData()
    } else {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('init', ({value}) => {
        this.setData({ post: value })
      })
    }
    
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    this.setData({
      user: app.globalData.user,

    })
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(val, pre) {
    let actions = []
    if (val.openid !== this.data.post?.openid) {
      actions = [
        {
          name: '互动',
          cb: e => this.go2interactCreate(e),
        }
      ]
    }
    this.setData({
      user: val,
      postActions: actions,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '详情',
      path: 'packageHome/pages/post-detail/index?id=' + this.data.id
    }
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  getData() {
    if (!this.data.id) return
    this.setData({
      loading: true,
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'get',
        data: this.data.id
      } 
    })
    .then(res => {
      let actions = []
      const p = res.result.data[0]
      if (this.data.user?.openid !== p?.openid) {
        actions = [
          {
            name: '互动',
            cb: e => this.go2interactCreate(e),
          }
        ]
      }
      this.setData({
        post: p,
        postActions: actions
      })
    })
    .catch((e) => this.toast({
      theme: 'fail',
      direction: 'column',
      message: '获取失败'
    }))
    .finally(() => {
      this.setData({
        loading: false,
      })
    })
  },
  go2interactCreate(e) {
    wx.navigateTo({
      url: '/packageInteract/pages/create/index',
      success: (res) => {
        res.eventChannel.emit('init', { post: e })
      },
    })
  },
  go2home() {
    wx.switchTab({
      url: '/page/home/index',
    })
  }
})